package com.yima.baseproj.config.validate.constraint.dict;

import cn.hutool.core.util.StrUtil;
import com.yima.baseproj.module.app.dict.data.AppDictDataService;
import com.yima.baseproj.utils.AppContextUtil;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author 一码
 * @description
 * @create 2021-01-29 11:12:33
 * @contact www.yanwei.xin 微信：13716343106 邮件：1424529270@qq.com
 **/
@Slf4j
public class ValidDictValidator implements ConstraintValidator<ValidDictEnum, Object> {
    private ValidDictEnum annotation;

    @Override
    public void initialize(ValidDictEnum constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (!annotation.isNotEmpty()) {
            return false;
        }

        if(value instanceof String){
            if(StrUtil.isBlank((String)value)){
                return false;
            }
        }
        AppDictDataService appDictDataService = AppContextUtil.getBean(AppDictDataService.class);
        long count = appDictDataService.countAllByTypeAndDataType(annotation.type(),String.valueOf(value));
        if(count == 0){
            return false;
        }

        return true;
    }
}
